<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="getTitle" width="650px" @ok="handleSubmit" showFooter destroyOnClose>
    <BasicForm @register="registerForm">
      <template #values="{ model, field }">
        <JVxeTable
          ref="tableRef"
          stripe
          toolbar
          keepSource
          rowSelection
          asyncRemove
          dragSort
          sortKey="sortNo"
          :auto-resize="true"
          :sync-resize="compData.activeKey"
          :maxHeight="450"
          :checkboxConfig="{ range: true }"
          :disabledRows="{ isPk: [true] }"
          :loading="compData.loading"
          :disabled="false"
          :columns="compData.columns"
          :dataSource="compData.dataSource"
          @removed="handleRemove"
        />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, useAttrs } from "vue"
  import { BasicForm, useForm, FormSchema } from "/@/components/Form/index"
  import { BasicDrawer, useDrawerInner } from "/@/components/Drawer"
  import { saveOrUpdateGoodsAttr } from "/@/api/bizShop/shop"
  import { useMessage } from "/@/hooks/web/useMessage"
  import { useI18n } from "/@/hooks/web/useI18n"
  import { JVxeTypes, JVxeColumn } from "/@/components/jeecg/JVxeTable/types"
  const { t } = useI18n("")

  const { createMessage } = useMessage()
  const emit = defineEmits(["success", "register"])
  const attrs = useAttrs()
  const isUpdate = ref(true)
  const record = ref<any>({})
  const tableRef = ref()

  const vxeColumns: JVxeColumn[] = [
    {
      title: "属性名称",
      key: "name",
      type: JVxeTypes.input,
      width: 200,
      validateRules: [{ required: true, message: "${title}不能为空" }],
    },
    {
      title: "加价（元）",
      key: "additionalPrice",
      type: JVxeTypes.inputNumber,
      defaultValue: "0",
      validateRules: [{ required: true, message: "${title}不能为空" }],
    },
  ]

  interface CompData {
    loading: boolean
    columns: JVxeColumn[]
    activeKey: string
    dataSource: Recordable[]
  }

  const compData = ref<CompData>({
    loading: false,
    columns: vxeColumns,
    activeKey: "",
    dataSource: [],
  })

  const inputFormSchemas: FormSchema[] = [
    {
      label: "id",
      field: "id",
      show: false,
      component: "Input",
    },
    {
      label: t("属性名"),
      field: "name",
      required: true,
      component: "Input",
    },
    {
      field: "multipleChoice",
      component: "RadioGroup",
      label: "是否多选",
      required: true,
      defaultValue: false,
      componentProps: {
        options: [
          { label: "不支持", value: false },
          { label: "支持", value: true },
        ],
      },
    },
    {
      field: "required",
      component: "RadioGroup",
      label: "是否必填",
      required: true,
      defaultValue: true,
      componentProps: {
        options: [
          { label: "必填", value: true },
          { label: "非必填", value: false },
        ],
      },
    },
    {
      label: t("排序号"),
      field: "sortNo",
      component: "InputNumber",
      defaultValue: "30",
      componentProps: {
        maxlength: 10,
      },
      rules: [{ required: true }, { pattern: /^\d+$/, message: t("请输入一个正整数") }],
    },
    {
      label: t("属性值"),
      field: "values",
      slot: "values",
      component: "Select",
    },
  ]
  const [registerForm, { setProps, resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 90,
    schemas: inputFormSchemas,
    showActionButtonGroup: false,
    wrapperCol: { lg: 24, md: 24 },
  })

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await resetFields()
    record.value = data.record
    setDrawerProps({ confirmLoading: false, loading: true })
    try {
      isUpdate.value = !!data?.isUpdate
      compData.value.dataSource = record.value.values
      if (isUpdate.value) {
        setFieldsValue({ ...record.value })
      }
    } finally {
      setDrawerProps({ loading: false })
    }
  })

  const getTitle = computed(() => (!unref(isUpdate) ? "新增属性" : "编辑属性"))

  const handleRemove = async (event) => {
    await tableRef.value!.removeSelection()
  }

  const validateAttrValue = async (callback: Function) => {
    const values = tableRef.value!.getTableData()
    for (const item in values) {
      const errMap = await tableRef.value!.validateTable(values[item])
      if (errMap) {
        console.log("表单验证未通过：", { errMap })
        if (callback) {
          callback()
        }
        await tableRef.value!.validateTable()
        throw new Error(errMap)
      }
    }
    return values
  }

  async function handleSubmit() {
    try {
      await validateAttrValue(() => {})
      const attrValue = tableRef.value!.getTableData()
      let formValue = await validate()
      setDrawerProps({ confirmLoading: true })

      await saveOrUpdateGoodsAttr({ ...formValue, values: attrValue }, unref(isUpdate))
      closeDrawer()
      createMessage.success(`${getTitle.value}成功`)
      emit("success")
    } finally {
      setDrawerProps({ confirmLoading: false })
    }
  }
</script>
